import React from 'react';

import 'moment-timezone';


import { Button, Modal, ModalFooter } from '@folio/stripes/components';

import { FormattedMessage } from 'react-intl';

class RevealQrCode extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      titleName: <FormattedMessage id={"ui-party.loans.columns.operating.qrcode"}/>,
      activityName: '',
      checkInDateTime: '',
      activityDateTime: '',
      registrationDateTime: '',
      files: props.files || []
    };
  }

    getCheckCodeImage = obj => {
      const type = obj.type;
      const openCodeImageObject = obj.openCodeImageObject;
      let titleName = '';
      if (type === 'check') {
        titleName = <FormattedMessage id={"ui-party.loans.columns.operating.reserve.qrcode"}/>;
      } else {
        titleName = <FormattedMessage id={"ui-party.loans.columns.operating.attend.qrcode"}/>;
      }
      const activityName = openCodeImageObject.partyName;
      const checkInDateTime = `${openCodeImageObject.attendStartDate}-${openCodeImageObject.attendEndDate}`;
      const activityDateTime = `${openCodeImageObject.partyStartDate}-${openCodeImageObject.partyEndDate}`;
      const registrationDateTime = `${openCodeImageObject.reserveStartDate}-${openCodeImageObject.reserveEndDate}`;
      this.setState({
        titleName,
        activityName,
        checkInDateTime,
        activityDateTime,
        registrationDateTime
      });

      this.httpImage(openCodeImageObject.id, type);
    };

    httpImage = (id, type) => {
      const okapi = this.props.okapi;
      const request = new XMLHttpRequest();
      let url = ''
      if (type==='check')
      {
          url =  okapi.url + '/party/info/qr_code_attend/'+id ;
      }else{
          url =  okapi.url + '/party/info/qr_code_reserve/'+id ;
      }
      request.responseType = 'blob';
      request.open('get', url, true);
      request.setRequestHeader('X-Okapi-Tenant', okapi.tenant);
      request.setRequestHeader('X-Okapi-Token', okapi.token);
      request.onreadystatechange = e => {
        if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
          const aLabel = document.createElement('a');
            aLabel.download = this.state.titleName + '.jpg';
            aLabel.style.display = 'none';
            aLabel.setAttribute('class', 'codeImageDown');
          const blob = new Blob([request.response]);
            aLabel.href = URL.createObjectURL(blob);
          document.body.appendChild(aLabel);
          const src = URL.createObjectURL(request.response);
          const f = {};
          f.type = 'image/jpeg';
          f.thumb = src;
          const files = this.state.files.concat(f);
          this.setState({
            files
          });
        }
      };
      request.send(null);
    };

    downCodeImage = () => {
      const aLabel = document.getElementsByClassName('codeImageDown')[0];

        aLabel.click();
      alert('图片下载成功! ');
    }

    pdfPrint = () => {
      const aLabel = document.getElementsByClassName('imageAction')[0];
        aLabel.style.display = 'none';
      window.print();
        aLabel.style.display = 'block';
    }

    _renderPreview = () => {
      if (this.state.files) {
        return this.state.files.map((item, idx) => {
          return (
                  <div className="upload-append-list">
                      <p>
                          <img
                              src={item.thumb}
                              style={{ width: '300px', height: '300px' }}
                            />
                        </p>
                    </div>
          );
        });
      } else {
        return null;
      }
    };

    render() {
        const {   intl } = this.props;
      const dismissible = true;
      const closeOnBackgroundClick = true;
      const categoryFooter = (
          <ModalFooter>
              <Button buttonStyle="primary" marginBottom0>
                  <FormattedMessage id="ui-activity.page.operating.save" />
                </Button>
              <Button>
                  <FormattedMessage id="ui-activity.page.operating.cancel" />
                </Button>
            </ModalFooter>
      );
      return (
          <Modal
              dismissible={dismissible}
              closeOnBackgroundClick={closeOnBackgroundClick} // 点击背景关闭
              open={this.props.openCodeImageFlag}
              label={this.state.titleName}
              onClose={this.props.checkInCode}
            >
              <div>
                  <div
                      style={{
                          width: '300px',
                          height: '300px',
                          textAlign: 'center',
                          margin: '0 auto'
                        }}
                      className="codeImageInfo"
                    >
                      {this._renderPreview()}
                    </div>
                  <div style={{ marginLeft: '32%' }}>
                      <div>
                          {`${intl.formatMessage({id:"ui-party.loans.columns.party.partyName"})}:${this.state.activityName}`}
                    </div>

                      {this.state.registrationDateTime != undefined &&
                        this.state.registrationDateTime != null &&
                        this.state.registrationDateTime != '' ? (
                          <div>
                              {`${intl.formatMessage({id:"ui-party.loans.columns.party.reserveDate"})}:${this.state.registrationDateTime}`}
                            </div>
                          ) : (
                            ''
                          )}
                      {this.state.checkInDateTime != undefined &&
                        this.state.checkInDateTime != null &&
                        this.state.checkInDateTime != '' ? (
                          <div>

                              {`${intl.formatMessage({id:"ui-party.loans.columns.party.attendDate"})}:${this.state.checkInDateTime}`}
                            </div>
                          ) : (
                            ''
                          )}

                      <div>
                          {`${intl.formatMessage({id:"ui-party.loans.columns.party.partyDate"})}:${this.state.activityDateTime}`}

                        </div>
                      <div className="imageAction">
                          <div>
                              <a onClick={() => {
                                  this.downCodeImage();
                                }}
                                >
                                 <FormattedMessage id={"ui-party.other.download.qr.code.image"}/>

                                </a>
                            </div>
                          <div>
                              <a onClick={() => {
                                  this.pdfPrint();
                                }}
                                >
                                  <FormattedMessage id={"ui-party.other.print.online"}/>

                                </a>
                            </div>


                        </div>

                    </div>
                </div>

            </Modal>
      );
    }
}

export default RevealQrCode;
